package user

import (
	"context"
	"trusteva/app/rbac/model"

	"trusteva/app/rbac/internal/svc"
	"trusteva/app/rbac/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUserListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserListLogic {
	return &UserListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserListLogic) UserList(req *types.UserListRo) (resp *types.UserListRsp, err error) {
	sess := l.svcCtx.DB.WithContext(l.ctx).Model(&model.User{})

	if req.Username != "" {
		sess = sess.Where("Username=?", req.Username)
	}
	if req.Login != "" {
		sess = sess.Where("Login=?", req.Login)
	}
	if req.Status != "" {
		sess = sess.Where("Status=?", req.Status)
	}

	var total int64
	if err := sess.Count(&total).Error; err != nil {
		return nil, err
	}
	var beans []model.User
	if err := sess.Order("ID DESC").Limit(req.Size).Offset((req.Page - 1) * req.Size).
		Find(&beans).Error; err != nil {
		return nil, err
	}

	resp = new(types.UserListRsp)
	resp.Total = total
	for _, v := range beans {
		var ac = types.UserWithId{
			Uid: v.ID,
			User: types.User{
				Username: v.Username,
				Login:    v.Login,
				Memo:     v.Memo,
				//Roles:    v.Roles.Unmarshal(),
				Status:  int(v.Status),
				Company: v.Company,
				Email:   v.Email,
			},
		}

		for _, roleId := range v.Roles.Unmarshal() {
			var role model.RoleConfig
			if err := l.svcCtx.DB.WithContext(l.ctx).Where("Id=?", roleId).
				First(&role).Error; err != nil {
				return nil, err
			}
			ac.Roles = append(ac.Roles, types.UserRole{
				RoleId:   roleId,
				RoleName: role.Name,
			})
		}

		resp.Items = append(resp.Items, ac)
	}

	return
}
